//
//  BingPremiseVc.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/5/25.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//  绑定楼盘

#import "BingPremiseVc.h"
#import "TraderMoveManToStoreCell.h"
#import "NodataCell.h"
#import "BrokerDataMange.h"
#import "UserModal.h"

#import "config.h"
#import "PremisesModel.h"
#import "MBProgressHUD+MJ.h"
#import "MJRefresh.h"
#import "NSString+category.h"

@interface BingPremiseVc ()<UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) NodataCell *nodataCell;
@property (strong, nonatomic) BrokerDataMange *dataManage;
//保存选择的标示（哪行是选中的）
@property (strong, nonatomic) NSMutableArray *seletedArrM;
@property(nonatomic,assign) NSInteger pageIndex;

@property (nonatomic,strong)NSArray *selectedArr;//保存选中的楼盘的名字

@end

@implementation BingPremiseVc
@synthesize dataArray,nodataCell,dataManage,tableView,seletedArrM;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initView];
    [self initNoDataCell];
    [self refreshData];
    
    
}

-(void)initView
{

   
     [self.titleView setMianTitle:@"绑定楼盘"];

    
    [[self.titleView doneBtn] setImage:nil forState:UIControlStateNormal];
    [[self.titleView doneBtn]setAttributedTitle:[NSString makeLineStyle:@"保存" color:[UIColor whiteColor] fontSize:14] forState:UIControlStateNormal];
    [[self.titleView doneBtn]setTag:100];
    [[self.titleView doneBtn]addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    [tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    

    
    dataManage = [[BrokerDataMange alloc]init];
}

-(void)refreshData
{
    [tableView reloadData];
    [nodataCell setState:nodataCellStateLoading];
   __weak typeof(self)bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        ResulteMod *resultMod= [dataManage premiseslistWithUserCode:self.coustomerCode];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (resultMod.resltState==ResultNetError) {
                
                [bself.nodataCell setState:nodataCellStateNetError];
                
            }else if (resultMod.resltState==ResultFail){
                
                [bself.nodataCell setCodeErrorTip:resultMod.resultCode];
            }else
            {
                
//                bself.dataArray = [[NSMutableArray alloc]initWithArray:resultMod.dataMod];
                [bself dealSelectSite:resultMod.dataMod];
                
                if (bself.dataArray.count == 0) {
                    
                    [bself.nodataCell setState:nodataCellStateNodata];
                }else{
                   
                    bself.seletedArrM = [NSMutableArray array];
                    for (int i = 0; i < dataArray.count; i ++) {
                        ;
                        PremisesModel  *model = [dataArray objectAtIndex:i];
                        BOOL isSeleted = NO;
                        NSNumber *value = [NSNumber numberWithBool:isSeleted];
                        NSString *key = model.premisesId;
                        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                        [dict setValue:value forKey:key];
                        [bself.seletedArrM addObject:dict];
                        
                    }

                    
                }
            }
            
            [bself.tableView.header endRefreshing];
            [bself.tableView reloadData];
        });
    });
}

#pragma mark 筛选出可选的楼盘
-(void)dealSelectSite:(NSArray *)arr{
    
    self.dataArray = [NSMutableArray array];
    for (PremisesModel *model in arr) {
        if ([model.selectStatus isEqualToString:@"1"]) {
            
            [self.dataArray addObject:model];
        }
    }
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (dataArray.count == 0 || dataArray == nil) {
        return 1;

    }
    return dataArray.count;
}

-(void)initNoDataCell
{
    nodataCell = [[NodataCell alloc]initWithFrame:self.tableView.frame];
    [nodataCell setState:nodataCellStateLoading];
    [[nodataCell refreshBtn]setTag:56];
    [nodataCell.refreshBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (dataArray.count == 0 || dataArray == nil ) {
        if (!nodataCell) {
            nodataCell = [[NodataCell alloc]initWithFrame:self.tableView.frame];
            [nodataCell setState:nodataCellStateLoading];
            [[nodataCell refreshBtn]setTag:56];
             [nodataCell.refreshBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
        }
        return nodataCell;
    }
    
    TraderMoveManToStoreCell *cell = [TraderMoveManToStoreCell cellWithTableView:self.tableView];
    PremisesModel *model = [dataArray objectAtIndex:indexPath.row];
    
    [cell setDataWith:model WithIsSelected:[self rowIsSeleted:indexPath withKey:model.premisesId]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (dataArray.count == 0 || dataArray == nil)
    {
        return self.tableView.frame.size.height;
    }
    return [TraderMoveManToStoreCell getHeight];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
     PremisesModel *model = [dataArray objectAtIndex:indexPath.row];
    [self changeSeleted:indexPath withKey:model.premisesId];
    [self.tableView reloadData];
    
}
-(void)btnOnclick:(UIButton *)btn
{
    NSInteger tag = btn.tag;
    switch (tag) {
        case 56:
            [self refreshData];
            break;
        case 100: //点击完成
            
        {
            if (self.vcState == PREVIOUSVC_LATENVC) {
                
    
                 [self bindpremisesWithPremisesIds:[self getSeletedIdStr]];

            }else if (self.vcState == PREVIOUSVC_ADDCUS)
            {
                if ([self getSeletedIdStr].length == 0 || ![self getSeletedIdStr]) {
                    
                    
                    [MBProgressHUD showError:@"请至少绑定一个楼盘"];
                    return;
                }
                [self getSeletedIdStr];
                [self.delegate bingPremiseVcSeletedSitesArr:self.selectedArr];
                [self.navigationController popViewControllerAnimated:YES];
            }else if (self.vcState == PREVIOUSVCf_EDit)
            {
                
                if ([self getSeletedIdStr].length == 0 || ![self getSeletedIdStr]) {
                    
                    
                    [MBProgressHUD showError:@"请至少绑定一个楼盘"];
                    return;
                }

                
                [self getSeletedIdStr];
                [self.delegate bingPremiseVcSeletedSites:nil];
                [self.navigationController popViewControllerAnimated:YES];
                
                
                
            }

            
        }
            break;
            
        default:
            break;
    }
    
}

#pragma mark 绑定楼盘
-(void)bindpremisesWithPremisesIds:(NSString *)PremisesIds
{
    if(PremisesIds.length == 0 || !PremisesIds)
    {
        [MBProgressHUD showError:@"请至少绑定一个楼盘"];
        return;
    }
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    
    __weak typeof(self) bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        ResulteMod *mod = [dataManage bindpremisesWithCustomerId:bself.coustomerId WithPremisesIds:PremisesIds];
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            if (mod.resltState == ResultFail) {
                [MBProgressHUD showError:mod.resultTip];
            }else if (mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络错误"];
            }else
            {
                [bself.navigationController popViewControllerAnimated:YES];
                [MBProgressHUD showSuccess:@"绑定成功"];
            }
        });
    });
    
    
}

#pragma mark 拼接被选中的楼盘的ID
-(NSString *)getSeletedIdStr
{
    NSMutableArray *seletedIdAr = [NSMutableArray array];
    NSMutableArray *seletedNameArr = [NSMutableArray array];
    
    NSMutableArray *lockSiteArrM = [NSMutableArray array];
    
    for (int i = 0; i < dataArray.count; i ++)
    {
        PremisesModel *model = [dataArray objectAtIndex:i];
       
        
        if ([model.bindStatus isEqualToString:@"1"]) {
            
            [seletedIdAr addObject:model.premisesId];
            [seletedNameArr addObject:model.premisesTitle];
            
            [lockSiteArrM addObject:model];
        }
        
    }
    [UserModal shareUserModel].prmisedNames = [seletedNameArr componentsJoinedByString:@","];
    [UserModal shareUserModel].premiseIds = [seletedIdAr componentsJoinedByString:@","];
    
    [UserModal shareUserModel].editLockSiteArr = [[NSArray alloc]initWithArray:lockSiteArrM];
    self.selectedArr = [[NSArray alloc]initWithArray:seletedNameArr];
    return  [seletedIdAr componentsJoinedByString:@","];

}

#pragma mark 返回第row行是否被选中
-(BOOL)rowIsSeleted:(NSIndexPath *)indexPath withKey:(NSString *)key;
{
    NSMutableDictionary *dic = [seletedArrM objectAtIndex:indexPath.row];

    NSNumber *value = [dic objectForKey:key];
    
    return   [value boolValue];;
}

#pragma mark 对第indexPath行的选中情况取反
-(void)changeSeleted:(NSIndexPath *)indexPath withKey:(NSString *)key
{
//    NSMutableDictionary *dict = [seletedArrM objectAtIndex:indexPath.row];
//    
//    NSNumber *value = [dict objectForKey:key];
//    BOOL isSeleted = [value boolValue];
//    value = [NSNumber numberWithBool:!isSeleted];
//    
//    [dict setObject:value forKey:key];
//    [seletedArrM  replaceObjectAtIndex:indexPath.row withObject:dict];
    
    PremisesModel *model = [dataArray objectAtIndex:indexPath.row];
    if ([model.bindStatus isEqualToString:@"1"]) {
         model.bindStatus = @"0";
    }else
    {
         model.bindStatus = @"1";
    }
      
    [dataArray replaceObjectAtIndex:indexPath.row withObject:model];
    
}
@end
